package View.LinearFilterTable;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: Andrew
 * Date: 10.03.12
 * Time: 0:47
 * To change this template use File | Settings | File Templates.
 */
public class LinearFilterTableCellEditor extends DefaultCellEditor implements TableCellEditor {
    // This is the component that will handle the editing of the cell value
    private JComponent component;
    private int rowIndex;
    private int vColIndex;
    private LinearFilterTableModel tableModel;

    public void stop() {
        super.stopCellEditing();
    }

    public LinearFilterTableCellEditor(LinearFilterTableModel tableModel){
        super(new JTextField());
        component = editorComponent;
        this.tableModel = tableModel;
    }

    // This method is called when a cell value is edited by the user.
    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected, int rowIndex, int vColIndex) {
        // 'value' is value contained in the cell located at (rowIndex, vColIndex)

        if (isSelected) {
            // cell (and perhaps other cells) are selected
        }

        // Configure the component with the specified value
        ((JTextField)component).setText((String) value.toString());
        
        this.rowIndex = rowIndex;
        this.vColIndex = vColIndex;

        // Return the configured component
        return component;
    }


    public boolean stopCellEditing() {
        /*Object obj = delegate.getCellEditorValue();
        if (obj is not an integer) {
            return false;
        }
        return true;  */
        String value = ((JTextField)component).getText();
        float x = 0;
        try {
            x =  Float.parseFloat(value);
            if (x < 0) {
                return false;
            }
            return super.stopCellEditing();
        } catch (Exception ex)
        {
            return false;
        }
    }

    // This method is called when editing is completed.
    // It must return the new value to be stored in the cell.
    public Object getCellEditorValue() {
        //String val = (String)defaultCellEditor.getCellEditorValue();
        String value = ((JTextField)component).getText();
        float x = 0;
        try {
            x =  Float.parseFloat(value);
            if (x < 0) {
                return null;
            }
        } catch (Exception ex)
        {
            return null;
        }
        tableModel.setRowDataAt(Float.parseFloat(value), rowIndex, vColIndex);
        return value;
    }
}
